package cn.sunxyz.module.honey.web;

import cn.sunxyz.common.site.Result;
import cn.sunxyz.module.honey.domain.FolderDO;
import cn.sunxyz.module.honey.domain.SiteDO;
import cn.sunxyz.module.honey.service.SiteService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.interceptor.TransactionAspectSupport;
import org.springframework.web.bind.annotation.*;

import javax.transaction.Transactional;
import java.util.HashSet;
import java.util.NoSuchElementException;
import java.util.Set;

/**
 * Created by sunxyz on 2017/3/2.
 */
@RestController
@RequestMapping("/api/site")
public class SiteController {

    private static final Logger logger = LoggerFactory.getLogger(SiteController.class);

    private static Result<String> ok;

    private static Result<String> error;

    static {
        ok = Result.ok("收藏成功", null);
        error = Result.error("收藏失败");
    }

    @Autowired
    private SiteService siteService;

    /**
     * 向文件夹添加链接
     * Created by sunxyz on 2017/3/3.
     */
    @GetMapping("folder/{folderId}/post")
    public Result<String> postFolderAddSite(@PathVariable("folderId") FolderDO folder, @RequestParam String url) {
        return folderAddSite(folder, url);
    }

    /**
     * 向文件夹添加链接
     * Created by sunxyz on 2017/3/3.
     */
    @Transactional
    @PostMapping
    public Result<String> folderAddSite(@RequestParam("folderId") FolderDO folder, String url) {
        try {
            Set<SiteDO> sites = folder.getSites();
            sites = sites != null ? sites : new HashSet<>();
            sites.add(siteService.getSiteByUrl(url));
            folder.setSites(sites);
            return ok;
        } catch (NoSuchElementException e) {
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            logger.error("向文件夹添加链接失败 : {}", e.getMessage());
            return error;
        }

    }

    /**
     * 从文件夹中移除某链接
     * Created by sunxyz on 2017/3/3.
     */
    @Transactional
    @DeleteMapping("/{siteId}")
    public Result<String> deleteSite(@RequestParam("folderId") FolderDO folder, @PathVariable("siteId") SiteDO siteDO) {
        Set<SiteDO> sites = folder.getSites();
        sites = sites != null ? sites : new HashSet<>();
        sites.remove(siteDO);
        folder.setSites(sites);
        return Result.ok();
    }

}
